const express = require('express')
// 导入bcrypt
var bcrypt = require('bcrypt')
const bodyParser = require('body-parser')
const stringRandom = require('string-random');
const jwt = require('jsonwebtoken')
const path = require('path')

const fs = require('fs')

const app = express()

require('./database/init')
const User = require('./model/User')

// 创建初始用户
async function initial() {
    let salt = await bcrypt.genSalt(10)
    let pass = await bcrypt.hash('123456', salt)
    let key = stringRandom(32)
    let admin = {
        username: 'admin',
        password: pass,
        email: 'admin@qq.com',
        key,
        role: 'admin'
    }
    const create = await User.create(admin)
    if (!create) {
        console.log('创建失败!');
        return
    }
    console.log(create);
}
// 查询数据库中是否存在 admin 管理员 用户不存在就创建
async function findUser() {
    const model = await User.findOne({ where: { role: 'admin' } })
    if (!model) {
        initial()
        return
    }
}
findUser()

// 设置跨域和相应数据格式  
app.all('/api/*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
    res.setHeader('Content-Type', 'application/json;charset=utf-8')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    if (req.method == 'OPTIONS') res.send(200)
    /*让options请求快速返回*/ else next()
})


app.use(express.static(path.join(__dirname, 'public')))

// 初始化统一响应机制
const resextra = require('./modules/resextra')
app.use(resextra)
app.use(bodyParser.urlencoded({ extended: false }))


// 拦截所有请求 进行 token 验证
app.use('/api', (req, res, next) => {
    if (req.url == '/login' || req.url == '/register' || req.url == '/fileupload' || req.url == '/fileimg' || req.url == '/getimg' || req.url == '/delimg' || req.url == '/sendemail') {
        next()
        return
    }
    // 接收客户端传递过来的 token
    const token = String(req.headers.authorization)
    // 根据 客户端传递过来的 token 进行 解析，解析成功返回一个对象，解析失败直接返回 null
    // 第一个参数是 token 第二个是 私钥 自己定义 
    const username = jwt.decode(token, 'xiaoke')
    // 判断是否传递 token 和 判断 token 是否 正确
    if (token == 'undefined' || username == null) {
        res.sendResult(null, 400, '无效token')
        return
    }
    next()
})

const main = require('./route/main')
app.use('/api', main)


console.log(path.join(__dirname));


app.listen('8888', () => {
    console.log('服务器启动成功');
})


